# -*- coding: utf-8 -*-

import configparser

from auto.untils import MySQLDictCursor

config = configparser.ConfigParser()
config.read("./config/config.ini", encoding='utf-8')


def get_conn():
    db = MySQLDictCursor(
        host=config['source']['host'],
        port=int(config['source']['port']),
        user=config['source']['user'],
        password=config['source']['password'],
        database=config['dict']['database']
    )

    return db.get_connection()


def insert():
    with get_conn() as conn:
        with conn.cursor() as cursor:
            server_ip_sql = f'select *  from sys_dict_item where type ="server_ip" order by id desc limit 1 '
            cursor.execute(server_ip_sql)

            row = cursor.fetchone()
            # for row in cursor:
            # print(row['sort'])

            row.pop('id')
            columns = ', '.join(row.keys())
            placeholders = ', '.join([f'%({key})s' for key in row.keys()])
            insert_query = f"INSERT INTO sys_dict_item ({columns}) VALUES ({placeholders})"
            row['description'] = '1,' + config['dict']['version']
            row['sort'] = row['sort'] + 1
            cursor.execute(insert_query, row)

            server_ip_sql2 = f'select *  from sys_dict_item where type ="service_gray" order by id desc limit 1 '
            cursor.execute(server_ip_sql2)

            row2 = cursor.fetchone()

            row2.pop('id')
            row2['description'] = config['dict']['version']
            row2['value'] = config['dict']['version']
            row2['label'] = config['dict']['version_name']
            row2['remarks'] = config['dict']['version_name'] + "服务器"
            row2['sort'] = row2['sort'] + 1
            cursor.execute(insert_query, row2)

            conn.commit()
            print("插入 server_ip 和  service_gray 成功")
